package net.maku.module.service.impl;

import net.maku.module.dao.AgCategoryDao;
import net.maku.module.entity.AgCategoryEntity;
import net.maku.module.query.AgCategoryPermissionQuery;
import net.maku.module.entity.AgCategoryPermission;
import net.maku.module.dao.AgCategoryPermissionDao;
import net.maku.module.service.AgCategoryPermissionService;
import net.maku.module.service.AgCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统用户管理栏目(AgCategoryPermission)表服务实现类
 *
 * @author ChiHongYu
 * @since 2025-01-08 13:23:13
 */
@Service("agCategoryPermission")
public class AgCategoryPermissionServiceImpl implements AgCategoryPermissionService {
    @Resource
    private AgCategoryPermissionDao agCategoryPermissionDao;
    @Autowired
    private AgCategoryDao agCategoryDao;

    @Autowired
    private AgCategoryService agCategoryService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public AgCategoryPermission queryById(Integer id) {
        return this.agCategoryPermissionDao.queryById(id);
    }

    @Override
    public AgCategoryPermission queryByRoleId(long roleId) {
        return this.agCategoryPermissionDao.queryByRoleId(roleId);
    }

    @Override
    public List<Long> getCategoryIdsByRoleIds(List<Long> roleIds) {
        if (roleIds.size() == 0) return new ArrayList<>();
        List<String> ids = agCategoryPermissionDao.getCategoryIdsByRoleIds(roleIds);
        Set<String> uniqueElements = new HashSet<>();
        for (String str : ids) {
            uniqueElements.addAll(Arrays.asList(str.split(",")));
        }
        String[] uniqueArray = uniqueElements.toArray(new String[0]);
        Arrays.sort(uniqueArray); // 如果需要排序
        return Arrays.stream(uniqueArray)
                .map(Long::parseLong)
                .collect(Collectors.toList());
    }


    @Override
    public List<AgCategoryPermission> queryByLimit(Map<String, Object> param, int limit1, int limit2) {
        return this.agCategoryPermissionDao.page(param, limit1, limit2);
    }

    @Override
    public int queryCount(Map<String, Object> param) {
        return this.agCategoryPermissionDao.count(param);
    }

    /**
     * 新增数据
     *
     * @param agCategoryPermission 实例对象
     * @return 是否成功
     */
    @Override
    public boolean insert(AgCategoryPermission agCategoryPermission) {
        return agCategoryPermissionDao.insert(agCategoryPermission) > 0;
    }

    /**
     * 修改数据
     *
     * @param agCategoryPermission 实例对象
     * @return 是否成功
     */
    @Override
    public boolean update(AgCategoryPermission agCategoryPermission) {
        return this.agCategoryPermissionDao.update(agCategoryPermission) > 0;
    }

    @Override
    public AgCategoryPermission insertOrUpdate(List<AgCategoryPermission> param, long executor) {
        //AgCategoryPermission categoryPermission = agCategoryPermissionDao.queryByRoleId(param.getSysRoleId());
        if (!CollectionUtils.isEmpty(param)) {

            Map data = new HashMap<>();

            Long categoryId = null;
            String categoryPermissionInfo = "";

            Map<Long, String> user = new HashMap();
            Boolean del = false;
            for (int i = 0; i < param.size(); i++) {
                AgCategoryPermission categoryPermission = param.get(i);

                if(null == categoryPermission.getUserId()){
                    del = true;
                }
                if (null == categoryId) {
                    categoryId = categoryPermission.getCategoryId();
                    categoryPermissionInfo = categoryPermission.getColumnPermissions();
                }

                if (!data.containsKey(categoryPermission.getCategoryId())) {
                    Map param1 = new HashMap<>();
                    param1.put("categoryId", categoryPermission.getCategoryId());
                    param1.put("columnPermissions", categoryPermission.getColumnPermissions());
                    agCategoryPermissionDao.deleteByCategoryId(param1);
                    data.put(categoryPermission.getCategoryId(), System.currentTimeMillis());
                }
                user.put(categoryPermission.getUserId(), System.currentTimeMillis() + "");


                this.insert(categoryPermission);

            }
            if (null != categoryId && !del) {
                //获取栏目所有上级
                AgCategoryEntity agCategoryEntity = agCategoryDao.selectById(categoryId);
                if (0 != agCategoryEntity.getParentId()) {
                    List<AgCategoryEntity> res = new ArrayList<>();
                    getParentList(agCategoryEntity.getParentId(), res);
                    if (!CollectionUtils.isEmpty(res)) {
                        for (Long key : user.keySet()) {
                            String finalCategoryPermissionInfo = categoryPermissionInfo;
                            res.forEach(e -> {
                                AgCategoryPermission agCategoryPermission = new AgCategoryPermission();
                                agCategoryPermission.setCategoryId(e.getId());
                                agCategoryPermission.setButtonPermissions("");
                                agCategoryPermission.setContentPermission("");
                                agCategoryPermission.setColumnPermissions(finalCategoryPermissionInfo);
                                agCategoryPermission.setUserId(key);

                                this.insert(agCategoryPermission);
                            });

                        }

                    }

                }
            }

            //Long categoryId = categoryPermission.getCategoryId();


            return null;
        }
        return null;

    }

    public List<AgCategoryEntity> getParentList(Integer parentId, List<AgCategoryEntity> res) {

        AgCategoryEntity agCategoryEntity = agCategoryDao.selectById(parentId);
        res.add(agCategoryEntity);
        if (0 == agCategoryEntity.getParentId()) {
            return res;
        }
        return getParentList(agCategoryEntity.getParentId(), res);

    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.agCategoryPermissionDao.deleteById(id) > 0;
    }

    /**
     * 通过主键修改使用状态
     *
     * @param id       主键
     * @param useState 使用状态
     * @return 是否成功
     */
    @Override
    public boolean changeUseById(Integer id, String useState) {
        return this.agCategoryPermissionDao.changeUseById(id, useState) > 0;
    }
}
